<template>
  <div class="sned">
    <van-action-sheet v-model="isshow" title="选择接收人员" @close="hadleClosed" style="height: 52%">
      <div class="content">
        <van-tree-select :items="items" :active-id.sync="activeIds" :main-active-index.sync="activeIndex" @click-item="handlerselect" />
      </div>
      <div style="position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%)">
        <van-button style="width: 90vw" type="info" @click="hadleConfirm">确定</van-button>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
import { QuerySignCallback, FileServerProxy } from '@/utils/api'
import { GSA_Add, GSA_Search } from '@/common/commonApi'
import { GJDBFunction2 } from '@/utils/queryData'
export default {
  data() {
    return {
      items: [],
      activeId: 1,
      activeIds: [],
      activeIndex: 0,
      personData: []
    }
  },
  props: {
    isshow: false,
    handleSelectClose: Function,
    //当前行数
    rowData: Object,
    //保存的数据
    JFData: Array
  },
  watch: {
    rowData: {
      handler(newdata, olddata) {
        console.log(newdata, 'efdedce')
        //判断如果是前三到场 发结束
        if (newdata.IF_TG == '6' || this.JFData[0].IF_TG == '6') {
          //浙政钉四道场 发送到农户整改的
          console.log("农户整改", 'efdedce')
          this.getPerson('农户整改')
        }
        //现场踏勘
        if (newdata.NODE_GUID == '{5E1AD806-7824-4196-8ADF-E231A8704FD3}') {
          this.getPerson('现场踏勘')
        }
        if (newdata.NODE_GUID == '{517211B4-3740-4F49-9DA4-7BC3C9A6F9EA}' || newdata.NODE_GUID == '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}') {
          this.getPerson('企业单位')
        }
        if (newdata.NODE_GUID == '{67241083-CA60-43FC-B1C1-1F4A2D133184}') {
          this.getPerson('现场踏勘2')
        }
        if (
          newdata.NODE_GUID == '{5821E9EB-44B5-49AC-A659-6DF98B410B38}' ||
          newdata.NODE_GUID == '{0439EC7A-785D-4B5B-ADD4-11E2D320376E}' ||
          newdata.NODE_GUID == '{417EFF61-5FA8-44D6-A624-5B3D0F39B56C}'
        ) {
          if (newdata.IsequitPerson == '是') {
            //发给批前公示
            this.getPerson('三方批前公示')
          } else if (newdata.IsequitPerson == '否') {
            //发给对应的负责人
          }
        }
        if (!newdata.NODE_GUID||newdata.NODE_GUID=='{A0C5F07B-1947-452D-942B-81D8A2095EBA}') {
          this.getPerson1('村预审')
        }

        //判断如果是三方经办人环节  并且三个经办人和三个负责人是同一个人的情况

        //判断如果是三方经办人环节  并且三个经办人和三个负责人是不是同一个人的情况
      },
      immediate: true, // 默认是false，watch在首次绑定amount时，是否立即执行handler函数
      deep: true
    }
  },
  mounted() {},
  created() {},
  methods: {
    hadleClosed() {
      this.handleSelectClose()
    },
    //获取要发送的人员
    /**
     *  农户整改发送逻辑
        放样是否通过 字段 为 否 时发送给农户进行整改 节点guid = {D2048C7B-88F9-453C-8FB9-6CFBE287634F} 发送人员 特定 USERID = '-1111'
        NAME= '农户';
        若为是 且 选择测绘单位 字段 为否 是就结束 结束节点guid = {F81FCB82-7196-4E94-BFF5-159E1CEBEFF8}
        测绘单位发送逻辑
            点击《选择测绘单位》 打开试图d87a95d9-72f3-44ad-a4d9-df335123a925 获得数据
            for (var i = 0; i < qy.length; i++) {
                bm2 += qy[i].COMAPNY_NAME + ",";
                id2 += qy[i].PKID + ",";
            }
            id2 赋值给 测绘单位ID        bm2 赋值给测绘单位名称
            在发送任务时候 如为‘是’ 是否选择测绘单位 则发送给id2 的人员
            如果‘否’ 则正常发送
            测绘单位节点GUID={B6C36D7F-E42E-49EC-B7EA-9CCF2449DB2A}
     *
     */
    wfGuid(nodeGuid) {
      if (!nodeGuid||nodeGuid == '{A0C5F07B-1947-452D-942B-81D8A2095EBA}') {
        //村预审
        return {
          wfGuid: '{AEA22B60-9184-42ED-9B8D-CEAE4A8F3021}',
          wfNodeGuid: '{5E1AD806-7824-4196-8ADF-E231A8704FD3}',
          I_TYPE: 9,
          wfNodeName: '村级预审'
        }
      } else if (nodeGuid == '{67241083-CA60-43FC-B1C1-1F4A2D133184}' ||nodeGuid == '{5E1AD806-7824-4196-8ADF-E231A8704FD3}' || nodeGuid == '{517211B4-3740-4F49-9DA4-7BC3C9A6F9EA}' || nodeGuid == '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}') {
        //现场踏勘
        return {
          wfGuid: '',
          wfNodeGuid: '{5E1AD806-7824-4196-8ADF-E231A8704FD3}',
          I_TYPE: 9,
          wfNodeName: '现场踏勘'
        }
      }
    },
    async hadleConfirm() {
      const wfGuid = this.wfGuid(this.rowData.NODE_GUID)
      let TASK_ID = ''
      if (wfGuid.wfGuid) {
        // 创建流程接口
        console.log(this.rowData.NODE_GUID,'this.rowData.NODE_GUID')
        if(this.rowData.NODE_GUID !='{A0C5F07B-1947-452D-942B-81D8A2095EBA}'){
          let NHApplyParam = {
          accessCode: '2c824ce489ff4cffaa0d77082e6fb648',
          cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
          params: {
            wfGuid: wfGuid.wfGuid,
            entityRowGuid: this.rowData.ROW_GUID
          }
        }
        const NHApplyresData = await FileServerProxy(NHApplyParam)
        let SendFNHApplyresData = JSON.parse(NHApplyresData.data.data)
        if (SendFNHApplyresData.ErrorMsg == '没有发起流程的权限！' || SendFNHApplyresData.ErrorCode == 'wf-001') {
          this.$toast.fail('没有发起流程的权限！')
          return false
        }
        }
        //获取人员信息以获取
        //任务信息
        let params = {
          accessCode: '3ec88931e2bf429d9ceadff8697b6772',
          cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
          params: {
            wfGuid: wfGuid.wfGuid,
            entityRowGuid: this.rowData.ROW_GUID,
            token: window.localStorage.getItem('token')
          }
        }
        const resCreate = await FileServerProxy(params)
        let resCreateData = JSON.parse(resCreate.data.data)
        TASK_ID = resCreateData.TaskId
      }
      //都要走这个接口
      let parms = {
        taskId: TASK_ID ? TASK_ID : this.rowData.TASK_ID,
        direction: 0,
        wfGuid: '{AEA22B60-9184-42ED-9B8D-CEAE4A8F3021}',
        wfBoxGuid: '',
        sendNodes: JSON.stringify(this.personData),
        actionTEXT: '同意',
        taskName: '浙里办',
        token: window.localStorage.getItem('token')
      }
      let params10 = {
        accessCode: 'c52bcf7cf3fb42bb9fbcd9b91e97d411',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: parms
      }
      const res = await QuerySignCallback(params10)
      if (eval('(' + res.data.data + ')').Success == true) {
        this.$toast.success('发送成功')
        //更新字段
        if (wfGuid.wfNodeName == '村级预审') {
          this.updateStatus()
        }
        //六元合一 需要下一个环节的node_guid
        let data1 = []
        this.personData.forEach(item=>{
          data1.push(item.wfNodeGuid)
        })
        this.senSixandOne(data1.toString())
        this.$router.push({
          path: "/MyTodoList",
        });
      }
    },

    //获取人员组合
    async getPerson(data) {
      let me = this
      me.items = []
      let params = {
        taskId: this.rowData.TASK_ID, //当前行的TASKID
        direction: 0,
        token: window.localStorage.getItem('token')
      }
      let params3 = {
        accessCode: '0a709d649c314903a72225edb8bc8c2a',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: params
      }
      const res = await FileServerProxy(params3)
      let newResData = JSON.parse(res.data.data)
      console.log(newResData)
      // me.tableData = eval('(' + res.data.data + ')')
      //如果是农户整改 节点名称只有农户
      if (data == '农户整改') {
        me.items.push({
          TEXT: '农户整改',
          WFNODEGUID: '{D2048C7B-88F9-453C-8FB9-6CFBE287634F}',
          dot: false,
          TNID: 1,
          PTNID: '-1',
          // 导航节点额外类名
          className: 'my-class',
          // 该导航下所有的可选项
          children: [
            {
              TEXT: '农户',
              WFNODEGUID: '{D2048C7B-88F9-453C-8FB9-6CFBE287634F}',
              dot: false,
              TNID: 2,
              PTNID: '1',
              // 导航节点额外类名
              className: 'my-class'
            }
          ]
        })
        return
      } else if (data == '现场踏勘') {
        let IFXT = this.JFData[0].IF_XT //是否需要协同踏勘 5 是 6 否
        let xtryid = this.JFData[0].XTRYID //协同踏勘人员id
        let IFCH = this.JFData[0].SFXZQYDW //是否需要测绘单位 5 是 6 否
        let chryid = this.JFData[0].QYDWID //测绘单位人员id
        let I_ZJCITY = this.rowData.VILLAGE
        let newUserTreeData = []
        let newItem1 = {}
        let newItem2 = {}
        let Node2 = {}
        let nid = 1
        //添加节点
        let Node1 = {}
        //如果是需要协同并且需要测绘单位
        if (IFXT == 5 || IFCH == 5) {
          //测绘单位
          // if (!xtryid || !chryid) {
          //   this.$toast.fail('请选择测绘单位||请选择踏勘部门')
          //   return
          // }
          if (IFXT == 5) {
            if (!xtryid) {
              this.$toast.fail('请选择踏勘部门')
              this.isshow = false
              return false
            }
            Node1.WFNODEGUID = '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}' //节点guid
            Node1.WFNODENAME = '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}' //节点名称
            Node1.WFNODETYPE = 2 //2. 普通节点，5， 汇聚节点
            Node1.TEXT = '踏勘部门审核' //节点显示名称
            Node1.text = '踏勘部门审核' //节点显示名称
            Node1.TNID = 1
            Node1.PTNID = 0
            Node1.children = []
            newUserTreeData.push(Node1)
            let str = xtryid.substring(0, xtryid.lastIndexOf(',')) //分隔最后一位逗号
            const person_Data = await GJDBFunction2('up_townaudit', [{ I_USERID: str, I_TYPE: 23 }])
            if (person_Data.length == 0) {
              this.$toast.fail('请联系镇街管理员核查 <镇街资格审核（经办人）> 是否已配置好案卷接受人员')
              return false
            } else {
              person_Data.forEach((item, index) => {
                nid = index + 1 //累加
                newItem1.TNID = nid
                newItem1.PTNID = 1
                newItem1.ISUSER = 1
                newItem1.AUTOCHECKED = false
                newItem1.USERID = item.ST_ID
                newItem1.TEXT = item.ST_NAME
                newItem1.text = item.ST_NAME
                newItem1.id = item.ST_ID
                newItem1.wfNodeGuid = Node1.WFNODEGUID
                newItem1.wfNodeType = Node1.WFNODETYPE
                newItem1.wfNodeName = Node1.WFNODENAME
                newUserTreeData.push(newItem1)
              })
            }
            me.items.push(Node1)
            me.items.forEach((item, index1) => {
              if (item.text == '踏勘部门审核') {
                item.children.push(newItem1)
              }
            })
          }
          if (IFCH == 5) {
            if (!xtryid) {
              this.$toast.fail('请选择企业单位')
              this.isshow = false
              return false
            }
            Node2.WFNODEGUID = '{517211B4-3740-4F49-9DA4-7BC3C9A6F9EA}' //节点guid
            Node2.WFNODENAME = '企业单位' //节点名称
            Node2.WFNODETYPE = 2 //2. 普通节点，5， 汇聚节点
            Node2.TEXT = '企业单位' //节点显示名称
            Node2.text = '企业单位' //节点显示名称
            Node2.TNID = 2
            Node2.PTNID = 0
            Node2.children = []
            newUserTreeData.push(Node2)
            let str2 = "'" + chryid.substring(0, chryid.lastIndexOf(',')) + "'"
            const person_Data2 = await GJDBFunction2('up_townaudit', [{ I_USERID: str2, I_TYPE: 22 }])
            if (person_Data2.length == 0) {
              this.$toast.fail('请联系镇街管理员核查 <镇街资格审核（经办人）> 是否已配置好案卷接受人员')
              return false
            } else {
              person_Data2.forEach((item, index) => {
                nid = index + 1 //累加
                newItem2.TNID = nid
                newItem2.PTNID = Node2.TNID
                newItem2.ISUSER = 1
                newItem2.AUTOCHECKED = false
                newItem2.USERID = item.ST_ID
                newItem2.TEXT = item.ST_NAME
                newItem2.text = item.ST_NAME
                newItem2.id = item.ST_ID
                newItem2.wfNodeGuid = Node2.WFNODEGUID
                newItem2.wfNodeType = Node2.WFNODETYPE
                newItem2.wfNodeName = Node2.WFNODENAME
                newUserTreeData.push(newItem2)
              })
            }
          }
          me.items.push(Node2)
          console.log(me.items, 'console.log(me.items)')
          me.items.forEach((item, index1) => {
            if (item.text == '企业单位') {
              item.children.push(newItem2)
            }
          })
        } else {
          const person_Data = await GJDBFunction2('up_townaudit', [{ I_USERID: I_ZJCITY, I_TYPE: 21 }])
          if (person_Data.length == 0) {
            this.$toast.fail('未获取到对应村镇管理人员')
          } else {
            me.items.push({
              TEXT: '图集选用',
              text: '图集选用',
              WFNODEGUID: '{1055401E-8D9C-4AA8-AE67-394146C627FA}',
              dot: false,
              TNID: 1,
              PTNID: '-1',
              id: 1,
              // 导航节点额外类名
              className: 'my-class',
              // 该导航下所有的可选项
              children: []
            })
            person_Data.forEach((item, index) => {
              me.items[0].children.push({
                TEXT: item.ST_NAME,
                text: item.ST_NAME,
                WFNODEGUID: '{1055401E-8D9C-4AA8-AE67-394146C627FA}',
                id: index,
                USERID: item.ST_ID,
                wfNodeName: '图集选用',
                dot: false,
                wfNodeType: 2,
                TNID: 2,
                ISUSER: 1,
                PTNID: '1',
                // 导航节点额外类名
                className: 'my-class'
              })
            })
          }
        }

        return
      } else if (data == '三方批前公示') {
      } else if (data == '企业单位') {
        let data = [
          { field: 'PROC_GUID', value: this.rowData.PROC_GUID },
          { field: 'NODE_GUID', value: '{5E1AD806-7824-4196-8ADF-E231A8704FD3}' }
        ]
        //复核鉴定结果
        const res = await GSA_Search('cdd56378-60dc-4e40-a7f1-9977a3efec7f', data)
        if (res.Data.length == 0) {
          this.$toast.fail('未获取到对应镇街管理员')
          return
        }
        var str = res.Data[0].TASK_RECIPIENTLIST
        var str2 = str.split(',')
        const person_Data2 = await GJDBFunction2('USERNAME', [{ I_USERID: str2[1] }])
        console.log(person_Data2, 'console.log(person_Data2)')
        if (person_Data2.length == 0) {
          this.$toast.fail('未配置人员')
          return
        }
        me.items.push({
          TEXT: '现场踏勘',
          text: '现场踏勘',
          WFNODEGUID: '',
          dot: false,
          TNID: 1,
          PTNID: -1,
          id: 1,
          WFNODENAME: '现场踏勘',
          WFNODETYPE: 2,
          children: []
        })
        person_Data2.forEach((item, index) => {
          me.items[0].children.push({
            TEXT: item.USERNAME,
            text: item.USERNAME,
            WFNODEGUID: '{67241083-CA60-43FC-B1C1-1F4A2D133184}',
            dot: false,
            TNID: index,
            AUTOCHECKED: false,
            SINGLEASSIGN: true,
            selected: true,
            ISUSER: 1,
            PTNID: 1,
            id: item.USERID,
            USERID: item.USERID,
            WFNODENAME: '现场踏勘',
            WFNODETYPE: 5
          })
        })
        return
      } else if (data == '现场踏勘2') {
        let I_ZJCITY = this.rowData.VILLAGE
        let IF_ZCTK = this.rowData.IF_ZCTK
        let XTRYID = this.rowData.XTRYID
        let Node1 = {}
        let newItem1 = {}
        let newUserTreeData = []
        if (IF_ZCTK == 5) {
          //发送踏勘审核
          Node1.WFNODEGUID = '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}' //节点guid
          Node1.WFNODENAME = '{4BF99B6A-E6EE-4A47-B3AE-B9CD2DBD1F3E}' //节点名称
          Node1.WFNODETYPE = 2 //2. 普通节点，5， 汇聚节点
          Node1.TEXT = '踏勘部门审核' //节点显示名称
          Node1.text = '踏勘部门审核' //节点显示名称
          Node1.TNID = 1
          Node1.PTNID = 0
          Node1.children = []
          newUserTreeData.push(Node1)
          let str = XTRYID.substring(0, XTRYID.lastIndexOf(',')) //分隔最后一位逗号
          const person_Data = await GJDBFunction2('USERNAME', [{ I_USERID: str }])
          if (person_Data.length == 0) {
            this.$toast.fail('请联系镇街管理员核查 <镇街资格审核（经办人）> 是否已配置好案卷接受人员')
            return false
          } else {
            person_Data.forEach((item, index) => {
              nid = index + 1 //累加
              newItem1.TNID = nid
              newItem1.PTNID = 1
              newItem1.ISUSER = 1
              newItem1.AUTOCHECKED = false
              newItem1.USERID = item.ST_ID
              newItem1.TEXT = item.ST_NAME
              newItem1.text = item.ST_NAME
              newItem1.id = item.ST_ID
              newItem1.wfNodeGuid = Node1.WFNODEGUID
              newItem1.wfNodeType = Node1.WFNODETYPE
              newItem1.wfNodeName = Node1.WFNODENAME
              newUserTreeData.push(newItem1)
            })
          }
          me.items.push(Node1)
          me.items.forEach((item, index1) => {
            if (item.text == '踏勘部门审核') {
              item.children.push(newItem1)
            }
          })
        } else {
          //发送农户
          const person_Data = await GJDBFunction2('up_townaudit', [{ I_USERID: I_ZJCITY, I_TYPE: 28 }])
          if (person_Data.length == 0) {
            this.$toast.fail('未获取到对应村镇管理人员')
          } else {
            me.items.push({
              TEXT: '图集选用',
              text: '图集选用',
              WFNODEGUID: '{1055401E-8D9C-4AA8-AE67-394146C627FA}',
              dot: false,
              TNID: 1,
              PTNID: '-1',
              id: 1,
              // 导航节点额外类名
              className: 'my-class',
              // 该导航下所有的可选项
              children: []
            })
            person_Data.forEach((item, index) => {
              me.items[0].children.push({
                TEXT: item.ST_NAME,
                text: item.ST_NAME,
                WFNODEGUID: '{1055401E-8D9C-4AA8-AE67-394146C627FA}',
                id: index,
                USERID: item.ST_ID,
                wfNodeName: '图集选用',
                dot: false,
                wfNodeType: 2,
                TNID: 2,
                ISUSER: 1,
                PTNID: '1',
                // 导航节点额外类名
                className: 'my-class'
              })
            })
          }
        }
        return
      }
      //先组合左侧树
      newResData.SendData.forEach((newItem) => {
        if (newItem.PTNID == '-1') {
          me.items.push({
            TEXT: item.TEXT,
            text: item.TEXT,
            WFNODEGUID: item.WFNODEGUID,
            dot: false,
            TNID: item.TNID,
            PTNID: item.PTNID,
            id: item.USERID,
            WFNODENAME: item.WFNODENAME,
            // 导航节点额外类名
            className: 'my-class',
            SINGLEASSIGN: item.SINGLEASSIGN,
            PREJUNCNODEGUID: item.PREJUNCNODEGUID,
            ISUSER: item.ISUSER,
            WFNODETYPE: item.WFNODETYPE
          })
        }
      })
      //再根据左侧树组合右侧树
      newResData.SendData.forEach((item) => {
        me.items.forEach((item1) => {
          if (item1.TNID == item.PTNID) {
            item1.children.push({
              TEXT: item.TEXT,
              text: item.TEXT,
              WFNODEGUID: item.WFNODEGUID,
              dot: false,
              TNID: item.TNID,
              PTNID: item.PTNID,
              id: item.USERID,
              WFNODENAME: item.WFNODENAME,
              // 导航节点额外类名
              className: 'my-class',
              SINGLEASSIGN: item.SINGLEASSIGN,
              PREJUNCNODEGUID: item.PREJUNCNODEGUID,
              ISUSER: item.ISUSER,
              WFNODETYPE: item.WFNODETYPE
            })
          }
        })
      })
      console.log(me.items)
    },
    //村预审
    async getPerson1(data) {
      const person_Data = await GJDBFunction2('up_townaudit', [{ I_USERID: this.rowData.VILLAGE, I_TYPE: 1 }])
      console.log(person_Data, 'person_Data')
      let maxtnid = 0
      let conformityPerson = []
      if (person_Data.length == 0) {
        this.$toast.fail('未获取到对应人员')
        return false
      }
      let newResData = person_Data
      //先组合左侧树
      let me = this
      me.items = []
      me.items.push({
        text: '现场踏勘',
        WFNODEGUID: '',
        dot: false,
        TNID: 1,
        PTNID: -1,
        // 导航节点额外类名
        className: 'my-class',
        // 该导航下所有的可选项
        children: []
      })
      newResData.forEach((item, index) => {
        me.items.forEach((item1) => {
          item1.children.push({
            text: item.ST_NAME,
            TEXT: item.ST_NAME,
            USERID: item.ST_ID,
            WFNODEGUID: '{5E1AD806-7824-4196-8ADF-E231A8704FD3}',
            dot: false,
            id: item.ST_ID,
            TNID: index,
            PTNID: '-1',
            AUTOCHECKED: false,
            wfNodeType: 2,
            ISUSER: 1,
            selected: true,
            // 导航节点额外类名
            className: 'my-class',
            wfNodeName: '现场踏勘'
          })
        })
      })
    },
    //更新状态
    async updateStatus() {
      let data = this.rowData
      data.ISDELETE = 2
      const res = await GSA_Add('931c475d-c6f3-41c0-8aef-28e20922db97', false, data)
    },

    //选择右边的人员
    handlerselect(data) {
      if (this.personData.length > 0) {
        let status = false
        this.activeIds.forEach((item) => {
          if (item != data.id) {
            status = true
          }
        })
        if (status) {
          this.personData.push(data)
        }
        let datas = []
        this.activeIds.forEach((item) => {
          this.personData.forEach((items) => {
            if (item == items.id) {
              datas.push(items)
            }
          })
        })
        this.personData = datas
      } else {
        this.personData.push(data)
      }
      console.log(this.personData)
    },
    //任务发送后六元合一处理同权限任务
    async senSixandOne(data1) {
      let data = [{I_NODE_GUID_NOW: this.rowData.NODE_GUID, I_NODE_GUID_NEXT: data1}]
      const person_Data2 = await GJDBFunction2('oneIsAll', data)
    }
  }
}
</script>

<style>
.sned {
  width: 100%;
  height: 100vh;
  overflow: auto;

  .content {
    padding: 10px 10px;
    position: relative;
  }
}
</style>
